﻿// -----------------------------------------------------------------------
// <copyright file="DataCommandManager.cs" company="">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace NetFramework.DataAccess
{
    using System;
    using System.Collections;
    using System.Configuration;
    using NetFramework.Configuration;
    using NetFramework.Diagnostics;

    /// <summary>
    /// DataCommandManager
    /// </summary>
    public class DataCommandManager
    {
        private const string DEFAULT_DATASOURCE_NAME = "DEFAULT_DATASOURCE_NAME";

		private static Hashtable _dataSources = null;
		private static IDataSource _defaultDataSource = null;

		static DataCommandManager()
		{
			LoadCache();
		}

		private static void LoadCache()
		{
			try
            {
                dataAccessSettings settings = ConfigManager.XmlConfig.GetConfig<dataAccessSettings>();
                Ensure.IstNull<dataAccessSettings>(settings, "dataAccessSettings");

				_dataSources = new Hashtable();
				foreach(dataSource ds in settings.dataSources)
				{
                    string dsProvider = ds.provider;
                    if(string.IsNullOrEmpty(dsProvider))
                    {
                        dsProvider = "SqlClient";
                    }

					DataProvider provider = 
						DataProviderFactory.GetDataProvider(dsProvider);

					DataSource dataSource = 
						new DataSource(ds.name, provider, ds.connectionString, 
						ds.dataOperationsPath, provider.ParameterNamePrefix,
						ds.commandTimeout);
					_dataSources.Add(dataSource.Name, dataSource);

					if(ds.isDefault) 
					{
						_defaultDataSource = dataSource;
					}
				}

                DataOperationFactory.Init(_dataSources);
			}
			catch(Exception e)
			{
				throw new DataAccessException("Error loading cache from config.", e);
			}
		}

		//only static methods
        private DataCommandManager() { }

		public static IDataSource GetDataSource()
		{
			return GetDataSource(DEFAULT_DATASOURCE_NAME);
		}

		public static IDataSource GetDataSource(string dataSourceName)
		{
			IDataSource ds = null;

			if(dataSourceName.Equals(DEFAULT_DATASOURCE_NAME)) 
				ds = _defaultDataSource;
			else
				ds = _dataSources[dataSourceName] as DataSource;

			if(ds == null) 
			{
				//TODO: specialize the exception, perhaps DataSourceNotFoundException
				throw new DataAccessException("DataSource with name '" + dataSourceName + "' not found.");
			}

			return ds;
		}

        public static IDataCommand GetCommand(string commandName)
        {
            return DataOperationFactory.GetCommand(commandName);
        }
    }
}
